// pages/cnCollege/cnCollege.js
const app = getApp();
var host = app.globalData.host;
var utils = app.globalData.utils;
var self = null;

Page({
  data: {
    themeColor: '',
    defaultColor: '',
    borderColor: '',
    list: [],
    keyword: '',
    timeoutVar: null,
    pageNumber: 1,
    totalPage: 1
  },
  onLoad: function (options) {
    self = this;
    self.getStyle();
    self.init();
  },
  getStyle() {
    self.setData({
      themeColor: app.globalData.themeColor,
      defaultColor: app.globalData.defaultColor,
      borderColor: app.globalData.borderColor
    })
  },
  init() {
    wx.request({
      url: host + '/lx/search/cnSchools',
      success: function (res) {
        if (res.data.status == 200) {
          self.setData({
            list: res.data.info.list,
            pageNumber: res.data.info.pageNumber,
            totalPage: res.data.info.totalPage
          });
        } else {
          console.log("error: " + res.data.msg);
        }
      }
    })
  },
  search(e) {
    self.setData({
      list: []
    })
    clearTimeout(self.data.timeoutVar);
    var t = setTimeout(function () {
      self.setData({
        keyword: e.detail.value
      })
      var url = host + '/lx/search/cnSchools';
      var params = {
        kw: self.data.keyword
      };
      var success = function (res) {
        if (res.status == 200) {
          self.setData({
            list: res.info.list,
            pageNumber: res.info.pageNumber,
            totalPage: res.info.totalPage
          });
        } else {
          console.log("error: " + res.msg);
        }
      }
      var fail = function (res) {
        console.log(res);
      };
      var complete = function () { };
      utils.request(url, params, success, fail, complete);
    }, 500);
    self.setData({
      timeoutVar: t
    })
  },
  selectSchool(e) {
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    prevPage.setData({
      cnSchoolId: e.currentTarget.dataset.schoolid,
      cnSchoolName: e.currentTarget.dataset.schoolname
    })
    wx.navigateBack({
      delta: 1
    })
  },
  scrollToBottom(e) {
    console.log(self.data.pageNumber + "/" + self.data.totalPage);
    if (self.data.pageNumber >= self.data.totalPage) {
      return;
    }
    var url = host + '/lx/search/cnSchools';
    var params = {
      kw: self.data.keyword,
      page: self.data.pageNumber + 1
    };
    var success = function (res) {
      if (res.status == 200) {
        var list = self.data.list.concat(res.info.list);
        self.setData({
          list: list,
          pageNumber: res.info.pageNumber,
          totalPage: res.info.totalPage
        });
      } else {
        console.log("error: " + res.msg);
      }
    }
    var fail = function (res) {
      console.log(res);
    };
    var complete = function () { };
    utils.request(url, params, success, fail, complete);
  }
})